package com.bdqn.controller;

import com.alibaba.fastjson.JSON;
import com.bdqn.common.Constants;
import com.bdqn.pojo.StorageRecord;
import com.bdqn.pojo.Supplier;
import com.bdqn.pojo.SysRole;
import com.bdqn.pojo.SysUser;
import com.bdqn.service.SysRoleService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/role")
public class RoleController {
    @Resource
    private SysRoleService sysRoleService;

    @GetMapping("/list")
    public String list(Model model) {
        List<SysRole> list = sysRoleService.getList();
        model.addAttribute("roleList", list);
        return "sysRole/list";
    }

    @GetMapping("/toUpdate/{roleid}")
    public String toUpdate(Model model, @PathVariable("roleid") Integer roleid) {
        SysRole sysRole = sysRoleService.queryId(roleid);
        model.addAttribute("sysRole", sysRole);
        return "sysRole/update";
    }

    @PostMapping("/update")
    public String update(HttpSession session, SysRole sysRole) {
        SysUser userSession = (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysRole.setUpdatedUserId(userSession.getId());
        boolean update = sysRoleService.update(sysRole);
        return "redirect:/role/list";
    }

    @ResponseBody
    @DeleteMapping("del/{roleid}")
    public String delete(@PathVariable("roleid") Integer roleid) {
        Map<String, Object> map = new HashMap<>();
        SysRole sysRole = sysRoleService.queryId(roleid);
        if (sysRole == null) {
            map.put("delResult", "notexist");
            return JSON.toJSONString(map);
        }
        boolean delete = sysRoleService.delete(roleid);
        map.put("delResult", delete ? "true" : "false");
        return JSON.toJSONString(map);
    }

    @GetMapping("/toAdd")
    public String toAdd() {
        return "sysRole/add";
    }

    @ResponseBody
    @GetMapping("/codeExist")
    public String codeExist(String code) {
        Map<String, Object> map = new HashMap<>();
        int num = -1;
        if (code.equals("")) {
            num = -1;
            map.put("msg", "角色编号不能为空！");
        } else {
            SysRole sysRole = sysRoleService.queryCode(code);
            if (sysRole == null) {
                num = 0;
            }
            if (sysRole != null) {
                num = 1;
            }
        }
        map.put("exist", num);
        return JSON.toJSONString(map);
    }

    @PostMapping("/add")
    public String doAdd(HttpSession session, SysRole sysRole) {
        sysRole.setCreatedUserId(((SysUser) session.getAttribute(Constants.USER_SESSION)).getId());
        boolean flag = sysRoleService.add(sysRole);
        return "redirect:/role/list";
    }
}
